package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollectionUtil;
import com.tanhua.dubbo.api.mongo.SoundApi;
import com.tanhua.model.mongo.Sound;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@DubboService
public class SoundApiImpl implements SoundApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 获取探花传音音频
     * @param gender 性别
     * @param alreadyGetId 已获取过的音频Id集合
     * @param excludeIds  不喜欢用户和好友用户的Id集合
     * @return 音频
     */
    @Override
    public Sound getOne(String gender, Set<String> alreadyGetId, List<Long> excludeIds) {
        //匹配用户性别,如果本机用户为男,则筛选条件为女(本机用户为女,筛选条件为男)
        Criteria condition = Criteria.where("gender").ne(gender);
        //如果没有已获取的音频id则不添加条件
        if (alreadyGetId!=null) {
            //如果有已获取的音频id则添加条件
            List<ObjectId> ids = alreadyGetId.stream().map(s -> {
                return new ObjectId(s);
            }).collect(Collectors.toList());
            //添加音频id不为获取过的条件
            condition.and("id").nin(alreadyGetId);
        }
        //如果没有需要过滤的用户Id则不添加条件
        if (excludeIds!=null){
            //添加userId不为需要过滤的userId
            condition.and("userId").nin(excludeIds);
        }
        //创建sound类聚合操作对象 参数1：对sound类进行操作 参数2：自己设置集合操作条件 参数3:从结果中取样，样本数量为1
        TypedAggregation<Sound> soundTypedAggregation = TypedAggregation.newAggregation(Sound.class, Aggregation.match(condition),Aggregation.sample(1));
        //聚合操作获得结果
        AggregationResults<Sound> results = mongoTemplate.aggregate(soundTypedAggregation, Sound.class);
        //从聚合操作结果中获得sound并返回
        List<Sound> sounds = results.getMappedResults();
        if (CollectionUtil.isEmpty(sounds)){
            //如果结果为空就返回一个空属性sound对象
            return new Sound();
        }
        return sounds.get(0);
    }


    /**
     * 存语音
     *
     * @param sound
     */
    @Override
    public void save(Sound sound) {
        mongoTemplate.insert(sound);
    }
}
